package com.bytedance.social.service.impl;

import com.alibaba.druid.support.json.JSONUtils;
import com.bytedance.social.common.AIChatThread;
import com.bytedance.social.common.JwtUtil;
import com.bytedance.social.common.StatusCode;
import com.bytedance.social.event.MsgToAiPublisher;
import com.bytedance.social.event.SendZhiPuChatEvent;
import com.bytedance.social.http.Choices;
import com.bytedance.social.http.ToAi;
import com.bytedance.social.http.User;
import com.bytedance.social.http.ZhiPu;
import com.bytedance.social.mapper.MessageMapper;
import com.bytedance.social.pojo.Message;
import com.bytedance.social.properties.ZhiPuAiProperties;
import com.bytedance.social.request.MessageActionRequest;
import com.bytedance.social.request.MessageChatRequest;
import com.bytedance.social.respones.MessageActionResponse;
import com.bytedance.social.respones.MessageChatResponse;
import com.bytedance.social.service.MessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class MessageServiceImpl implements MessageService {


    @Autowired
    private MessageMapper messageMapper;

    @Autowired
    private ZhiPuAiProperties puAiProperties;

    @Autowired
    MsgToAiPublisher msgToAiPublisher;

    @Autowired
    private RestTemplate restTemplate;

    @EventListener
    public void onEvent(SendZhiPuChatEvent sendZhiPuChatEvent) {
        //监听到发送给AI的事件
        AIChatThread aiChatThread = new AIChatThread();
        aiChatThread.setRestTemplate(restTemplate);
        aiChatThread.setSendZhiPuChatEvent(sendZhiPuChatEvent);
        aiChatThread.setPuAiProperties(puAiProperties);
        aiChatThread.setMessageMapper(messageMapper);
        Thread thread = new Thread(aiChatThread);
        thread.start();
    }

    /**
     * 客户端通过定时轮询服务端接口查询消息记录
     * /douyin/message/chat/ - 聊天记录
     * 当前登录用户和其他指定用户的聊天消息记录
     * response
     * required int32 status_code = 1; // 状态码，0-成功，其他值-失败
     * optional string status_msg = 2; // 返回状态描述
     * repeated Message message_list = 3; // 消息列表
     *
     * @param messageChatRequest
     * @return
     */
    @Override
    public MessageChatResponse getUserMessageChat(MessageChatRequest messageChatRequest) {
        Long currentUserId = JwtUtil.parseToken(messageChatRequest.getToken());
        Long toUserId = messageChatRequest.getTo_user_id();
        Long preMsgTime = messageChatRequest.getPre_msg_time();
        /**
         * 根据上一条消息时间查询有无最新的消息，无则返回
         */
        //根据id查询message表获取message
        //子查询合并后按照时间排序
        List<Message> messageList = messageMapper.selectMessageById(currentUserId, toUserId, preMsgTime);
        MessageChatResponse messageChatResponse = new MessageChatResponse();
        messageChatResponse.setMessage_list(messageList);
        messageChatResponse.setStatus_msg("查询消息记录成功！");
        messageChatResponse.setStatus_code(StatusCode.STATUS_OK);
        return messageChatResponse;
    }

    /**
     * 登录用户对消息的相关操作，目前只支持消息发送
     * request
     * required string token = 1; // 用户鉴权token
     * required int64 to_user_id = 2; // 对方用户id
     * required int32 action_type = 3; // 1-发送消息
     * required string content = 4; // 消息内容
     * <p>
     * response
     * required int32 status_code = 1; // 状态码，0-成功，其他值-失败
     * optional string status_msg = 2; // 返回状态描述
     *
     * @param messageActionRequest
     * @return
     */
    @Override
    @Transactional
    public MessageActionResponse actionMessage(MessageActionRequest messageActionRequest) {
        //解析出当前currentUserId
        Long currentUserId = JwtUtil.parseToken(messageActionRequest.getToken());
        Long toUserId = messageActionRequest.getTo_user_id();
        String content = messageActionRequest.getContent();
        Integer actionType = messageActionRequest.getAction_type();
        Message message = new Message();
        message.setContent(content);
        message.setFrom_user_id(currentUserId);
        message.setTo_user_id(toUserId);
        long currentTimeMillis = System.currentTimeMillis();
        message.setCreate_time(currentTimeMillis);
        MessageActionResponse messageActionResponse = new MessageActionResponse();
        if (actionType == 1) {
            //目前只支持发送消息
            //判断to_user_id是不是人工智能的id
            messageMapper.insertUserMessage(message);
            if (toUserId == puAiProperties.getAIId()) {
                //基于事件发布通知
                SendZhiPuChatEvent sendZhiPuChatEvent = new SendZhiPuChatEvent(message);
                msgToAiPublisher.sendZhiPuAiEvent(sendZhiPuChatEvent);
                messageActionResponse.setStatus_code(StatusCode.STATUS_OK);
                messageActionResponse.setStatus_msg("发送成功！");
                return messageActionResponse;
            }
        }

        messageActionResponse.setStatus_code(StatusCode.STATUS_OK);
        messageActionResponse.setStatus_msg("发送成功！");
        return messageActionResponse;
    }


}
